package testJdk.base.juc_test.read_write_lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName : learn_jdk.base.juc_test.read_write_lock.TestReadWriteLock
 * @Description : 类描述
 * Created by cyd on 2021-10-25 11:11:01
 */
public class TestReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.read();
                }
            }).start();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.write(10);
            }
        }).start();
    }
}

class ReadWriteLockDemo {
    private int number = 0;

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ",read:" + number);
        } finally {
            lock.readLock().unlock();
        }
    }

    public void write(int number) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ",write:" + number);
        } finally {
            lock.writeLock().unlock();
        }

        this.number = number;
    }
}